package com.bcbim.api_web.sys.interceptor;

import com.bcbim.api_web.sys.init.code.CodeMap;
import com.bcbim.common.response.annotation.TranslationField;
import com.bcbim.common.sys.Constant;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Field;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * @Description: 码值翻译处理
 * @Author haoshuai
 * @Date 2020/8/27
 * @Version V1.0
 **/
@Slf4j
public class TranslateHandle {

    /**
     * @Description: 翻译数据
     * @Param: Object o 需要翻译的对象
     * @Author: haoshuai
     * @Date: 2020/8/27
     */
    public static Object translationData(Object o) {
        if(o instanceof List){
            Collection collection = (Collection<?>) o;
            if (CollectionUtils.isNotEmpty(collection)) {
                collection.stream().forEach(obj -> {
                    translateObject(obj);
                });
            }
        } else {
            translateObject(o);
        }
        return o;
    }

    private static void translateObject(Object o) {
        if (o == null) return;
        Field[] fields = o.getClass().getDeclaredFields();
        for (Field f : fields) {
            translateField(o, f);
        }
    }

    private static void translateField(Object o, Field f) {
        f.setAccessible(true);
        Object fieldValue = null;
        try {
            fieldValue = f.get(o);
        } catch (IllegalAccessException e) {
            log.error("字典翻译失败, errMsg={}", e);
        }
        TranslationField annotation = f.getAnnotation(TranslationField.class);
        if (null != annotation && null != fieldValue && StringUtils.isNotEmpty(annotation.typeFlag())) {
            translate(o, f, fieldValue, annotation);
        }
    }

    private static void translate(Object o, Field f, Object fieldValue, TranslationField annotation) {
        String val = String.valueOf(fieldValue);
        String typeFlag = annotation.typeFlag();
        String mapName = CodeMap.CODE_MAPPING.get(typeFlag).replace(Constant.TYPE_SUFFIX, Constant.MAP_SUFFIX);
        try {
            Map<String, String> codeMap =
                    (Map<String, String>) CodeMap.class.getField(mapName).get(null);
            f.set(o, codeMap.get(val));
        } catch (IllegalAccessException e) {
            log.error("字典翻译失败, errMsg={}", e);
        } catch (NoSuchFieldException e) {
            log.error("字典翻译失败, errMsg={}", e);
        }
    }

}
